<template>
  <div class="container">
    <!--搜索表单-->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form" @submit.native.prevent>
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入学员姓名"
            clearable
            @keyup.enter.native="onSubmit"
          />
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="searchForm.classId" placeholder="请选择班级" clearable>
            <el-option
              v-for="cls in classes"
              :key="cls.id"
              :label="cls.name"
              :value="cls.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="onSubmit">搜索</el-button>
          <el-button icon="el-icon-refresh-right" size="small" @click="clear">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--操作按钮-->
    <div class="brand-container">
      <div class="title-container">
        <span>学员列表</span>
      </div>
      <div class="button-group-container">
        <el-button type="info" size="small" icon="el-icon-download" @click="downloadStudentTemplate">下载模板</el-button>
        <el-upload
          ref="upload"
          class="upload-button"
          action="/api/file/upload/student"
          :headers="token"
          :show-file-list="false"
          :auto-upload="true"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
          accept=".xls,.xlsx"
        >
          <el-button type="success" size="small" icon="el-icon-upload2">开始导入</el-button>
        </el-upload>
        <el-button type="warning" size="small" icon="el-icon-download" @click="exportStudentData">导出数据</el-button>
      </div>
      <div class="align-right">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleEdit()">新增学员</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDelete()">批量删除</el-button>
      </div>
    </div>

    <!--数据表格-->
    <div class="table-container">
      <el-table
        ref="table"
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="studentNo" label="学号" align="center" />
        <el-table-column label="头像" align="center">
          <template slot-scope="{row}">
            <el-image
              v-if="row.avatar"
              style="width: 40px; height: 40px; border-radius: 50%"
              :src="row.avatar"
              :preview-src-list="[row.avatar]"
              fit="cover"
            />
            <el-avatar v-else :size="40">{{ row.name ? row.name.charAt(0) : '' }}</el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" align="center" />
        <el-table-column prop="email" label="邮箱" align="center" />
        <el-table-column label="班级" align="center">
          <template slot-scope="{row}">
            <span>{{ getClassName(row.classId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center">
          <template slot-scope="{row}">
            <span>{{ row.gender === 1 ? '男' : '女' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="{row}">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '在读' : '已离开' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="180" align="center">
          <template slot-scope="{row}">
            <el-button type="text" size="small" @click="handleEdit(row.id)">编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--分页工具条-->
    <div class="pagination-container">
      <el-pagination
        :background="true"
        :current-page="searchForm.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑数据对话框表单 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="resetForm">
      <el-form ref="studentForm" :model="student" :rules="rules" label-width="80px">
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action="/api/file/upload/avatar"
            :headers="token"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="student.avatar" :src="student.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="student.studentNo" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="student.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="student.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="student.gender" placeholder="请选择性别" style="width:100%">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="student.classId" placeholder="请选择班级" style="width:100%">
            <el-option
              v-for="cls in classes"
              :key="cls.id"
              :label="cls.name"
              :value="cls.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="student.status" placeholder="请选择状态" style="width:100%">
            <el-option label="在读" :value="1" />
            <el-option label="已离开" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="入学日期" prop="joinDate">
          <el-date-picker
            v-model="student.joinDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%;"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker
            v-model="student.birthDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%;"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { page, add, update, deleteByIds, getById } from '@/api/student'
import { findAll as findAllClasses } from '@/api/classes'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      loading: false,
      searchForm: {
        name: '',
        classId: '',
        page: 1,
        pageSize: 5
      },
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      student: {
        avatar: '',
        studentNo: '',
        name: '',
        email: '',
        gender: '',
        classId: '',
        status: '',
        joinDate: '',
        birthDate: ''
      },
      rules: {
        studentNo: [{ required: true, message: '请输入学号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
        classId: [{ required: true, message: '请选择班级', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        joinDate: [{ required: true, message: '请选择入学日期', trigger: 'change' }]
      },
      classes: [],
      multipleSelection: [],
      tableData: [],
      token: { token: getToken() }
    }
  },

  mounted() {
    this.page()
    this.loadClasses()
  },

  methods: {
    page() {
      this.loading = true
      page(this.searchForm).then(res => {
        this.total = res.data.data.total
        this.tableData = res.data.data.rows
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    loadClasses() {
      findAllClasses().then(res => {
        this.classes = res.data.data
      })
    },

    getClassName(classId) {
      const cls = this.classes.find(c => c.id === classId)
      return cls ? cls.name : '未知班级'
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    onSubmit() {
      this.searchForm.page = 1
      this.page()
    },

    clear() {
      this.searchForm = {
        name: '',
        classId: '',
        page: 1,
        pageSize: 5
      }
      this.page()
    },

    handleEdit(id) {
      this.dialogTitle = id ? '编辑学员' : '新增学员'
      if (id) {
        getById(id).then(res => {
          this.student = res.data.data
        })
      }
      this.dialogVisible = true
    },

    handleDelete(id) {
      const ids = id ? [id] : this.multipleSelection.map(item => item.id)
      if (ids.length === 0) {
        this.$message.warning('请选择要删除的数据')
        return
      }
      this.$confirm('此操作将永久删除所选数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteByIds(ids).then(() => {
          this.$message.success('删除成功')
          this.page()
        })
      }).catch(() => {})
    },

    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.page()
    },

    handleCurrentChange(val) {
      this.searchForm.page = val
      this.page()
    },

    resetForm() {
      this.student = {
        avatar: '',
        studentNo: '',
        name: '',
        email: '',
        gender: '',
        classId: '',
        status: '',
        joinDate: '',
        birthDate: ''
      }
      this.$refs.studentForm.resetFields()
    },

    submitForm() {
      this.$refs.studentForm.validate(valid => {
        if (valid) {
          const action = this.student.id ? update(this.student) : add(this.student)
          action.then(() => {
            this.$message.success(this.student.id ? '修改成功' : '新增成功')
            this.dialogVisible = false
            this.page()
          })
        }
      })
    },

    handleAvatarSuccess(res, file) {
      this.student.avatar = res.data
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    handleUploadSuccess(res, file) {
      this.$message.success('数据导入成功')
      this.page()
    },

    handleUploadError() {
      this.$message.error('数据导入失败')
    },

    beforeUpload(file) {
      this.$message.info('正在导入数据，请稍候...')
      return true
    },

    exportStudentData() {
      // 通过 /api/file/export/student 接口导出数据
      window.open('/api/file/export/student')
      this.$message.success('正在导出数据...')
    },

    downloadStudentTemplate() {
      window.open('/api/file/download/student')
    }
  }
}
</script>

<style>
.container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
}
.search-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 20px;
}
.search-form .el-form-item {
  margin-bottom: 0;
}
.search-button, .reset-button {
  margin-left: 10px;
}
.brand-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.title-container {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  display: flex;
  align-items: center;
}
.title-container .el-icon-tickets {
  margin-right: 8px;
  color: #409eff;
}
.button-group-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-grow: 1;
  margin-left: 20px;
}
.button-group-container > * + * {
  margin-left: 10px;
}
.align-right {
  display: flex;
  align-items: center;
}
.align-right > .el-button + .el-button {
  margin-left: 10px;
}
.upload-button {
  display: inline-block;
}
.table-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}
.pagination-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  margin-top: 20px;
  text-align: right;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<style>
/* 暗色主题适配：仅在 body.dark-theme 下生效 */
body.dark-theme .container,
body.dark-theme .search-container,
body.dark-theme .brand-container,
body.dark-theme .table-container,
body.dark-theme .pagination-container {
  background-color: #1f1f1f !important;
  color: #fff !important;
}

body.dark-theme .el-table,
body.dark-theme .el-table th,
body.dark-theme .el-table td {
  background-color: #232323 !important;
  color: #fff !important;
}

body.dark-theme .el-table__body tr:hover > td {
  background-color: #2b2b2b !important;
}

body.dark-theme .el-input__inner,
body.dark-theme .el-select .el-input__inner {
  background-color: #232323 !important;
  color: #fff !important;
  border-color: #444 !important;
}

body.dark-theme .el-button--primary {
  background-color: #409eff !important;
  border-color: #409eff !important;
  color: #fff !important;
}
body.dark-theme .el-button--danger {
  background-color: #f56c6c !important;
  border-color: #f56c6c !important;
  color: #fff !important;
}
body.dark-theme .el-button--success {
  background-color: #67c23a !important;
  border-color: #67c23a !important;
  color: #fff !important;
}
body.dark-theme .el-button--info {
  background-color: #909399 !important;
  border-color: #909399 !important;
  color: #fff !important;
}
body.dark-theme .el-button--warning {
  background-color: #e6a23c !important;
  border-color: #e6a23c !important;
  color: #fff !important;
}

body.dark-theme .el-pagination,
body.dark-theme .el-pagination__total,
body.dark-theme .el-pagination__jump,
body.dark-theme .el-pagination__editor,
body.dark-theme .el-pagination__sizes,
body.dark-theme .el-pagination__sizes .el-input__inner {
  background-color: #1f1f1f !important;
  color: #fff !important;
  border-color: #444 !important;
}

body.dark-theme .el-dialog {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-dialog__header {
  background-color: #232323 !important;
  color: #fff !important;
  border-bottom: 1px solid #444 !important;
}
body.dark-theme .el-dialog__title {
  color: #fff !important;
}
body.dark-theme .el-dialog__body {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-form-item__label {
  color: #fff !important;
}
body.dark-theme .el-select-dropdown {
  background-color: #232323 !important;
  color: #fff !important;
}
body.dark-theme .el-select-dropdown__item.selected {
  background-color: #409eff !important;
  color: #fff !important;
}
body.dark-theme .el-select-dropdown__item:hover {
  background-color: #2b2b2b !important;
  color: #fff !important;
}
body.dark-theme .el-tag.el-tag--success {
  background-color: #1f1f1f !important;
  color: #67c23a !important;
  border-color: #67c23a !important;
}
body.dark-theme .el-tag.el-tag--danger {
  background-color: #1f1f1f !important;
  color: #f56c6c !important;
  border-color: #f56c6c !important;
}
</style>
